package com.shrfid.rfidsdk.card;


import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.util.Log;

import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.util.SerialInputOutputManager;
import com.rfid.common.log.LogUtils;
import com.shrfid.module_base.util.ByteUtils;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 读者证读卡器服务,用于提供读卡功能
 */
public enum MC900ReadCardManager {

    INSTANCE;

    private final String TAG = "MC900ReadCardManager";


    private static final byte[] READ_CARD = new byte[]{0x36, 0x30, 0x30, 0x31, 0x45, 0x46, 0x38, 0x45, 0x03};

    private byte[] bufferReader = new byte[50];

    private int position = 0;

    private IonCardListener onCardListener;

    private UsbSerialDriver sDriver;

    private final ExecutorService mExecutor = Executors.newSingleThreadExecutor();

    private SerialInputOutputManager mSerialIoManager;

    private final SerialInputOutputManager.Listener mListener = new SerialInputOutputManager.Listener() {

        @Override
        public void onRunError(Exception e) {
            Log.d(TAG, "Runner stopped.");
        }

        @Override
        public void onNewData(final byte[] data) {
            decode(data);
        }
    };


    public void init(Context context) {
        UsbManager mUsbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        for (final UsbDevice device : mUsbManager.getDeviceList().values()) {
            final List<UsbSerialDriver> drivers = UsbSerialProber.probeSingleDevice(mUsbManager, device);
            Log.d(TAG, "Found usb device: " + device);
            if (!drivers.isEmpty()) {
                UsbSerialDriver driver = drivers.get(0);
                if (device.getVendorId() == 0x10c4 && device.getProductId() == 0xEA60) {
                    open(driver);
                    break;
                }
            }
        }
    }

    private void open(UsbSerialDriver driver) {
        sDriver = driver;
        try {
            sDriver.open();
            sDriver.setParameters(9600, 8, UsbSerialDriver.STOPBITS_1, UsbSerialDriver.PARITY_NONE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        stopIoManager();
        startIoManager();
    }

    private void stopIoManager() {
        if (mSerialIoManager != null) {
            Log.i(TAG, "Stopping io manager ..");
            mSerialIoManager.stop();
            mSerialIoManager = null;
        }
    }

    private void startIoManager() {
        if (sDriver != null) {
            Log.i(TAG, "Starting io manager ..");
            mSerialIoManager = new SerialInputOutputManager(sDriver, mListener);
            mExecutor.submit(mSerialIoManager);
        }
    }

    public void setOnCardListener(IonCardListener onCardListener) {
        this.onCardListener = onCardListener;
    }

    private void decode(byte[] bytes) {
        if (bytes != null && bytes.length > 0) {
            if (position < bufferReader.length - bytes.length) {
                System.arraycopy(bytes, 0, bufferReader, position, bytes.length);
                position += bytes.length;
                //36开头 03结尾
                if (bufferReader[0] == 0x36 && bufferReader[position - 1] == 0x03) {
                    LogUtils.v("onDataReceived:" + ByteUtils.bytesToHexString(bufferReader));
                    //8位读者证
                    if (position == 29) {
                        byte[] result = new byte[8];
                        int index = 6;
                        for (int i = 0; i < 8; i++) {
                            result[i] = bufferReader[index + 1];
                            index += 2;
                        }
                        String s = new String(result);
                        if (onCardListener != null) {
                            onCardListener.onCardListener(s);
                        }
                        LogUtils.v("MC900 读卡卡号:" + s);
                    } else if (position == 31 || position == 33) {  //10位读者证
                        byte[] result = new byte[10];
                        int index = 6;
                        for (int i = 0; i < 10; i++) {
                            result[i] = bytes[index + 1];
                            index += 2;
                        }
                        String s = new String(result);
                        if (onCardListener != null) {
                            onCardListener.onCardListener(s);
                        }
                        LogUtils.v("MC900 读卡卡号:" + s);
                    }
                    position = 0;
                    Arrays.fill(bufferReader, (byte) 0);

                }
            } else {
                position = 0;
                Arrays.fill(bufferReader, (byte) 0);
            }
        } else {
            position = 0;
            Arrays.fill(bufferReader, (byte) 0);
        }
    }

    public boolean readCardNo() {
        boolean isSuccess = true;
        try {
            sDriver.write(READ_CARD, 1000);
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof IOException) {
                isSuccess = false;
            }
        }
        return isSuccess;
    }

    public void close() {
        try {
            if (sDriver != null) {
                sDriver = null;
            }
            //sDriver.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public interface IonCardListener {
        void onCardListener(String card);
    }
}
